<template>
  <div class='container'>
    <!-- 卡片 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item v-if="$route.query.id">{{$route.query.name}}</el-breadcrumb-item>
          <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 卡片主题内容 -->
      <!-- 表单 -->
      <div class="formData">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="form">
          <el-form-item label="目录名称" prop="directoryName">
            <el-input v-model="formInline.directoryName"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-select v-model="formInline.state" placeholder="请选择">
              <el-option label="已启用" value="1"></el-option>
              <el-option label="已禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetForm">清除</el-button>
            <el-button type="primary" @click="searchResult">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="rightAdd">
          <i class="el-icon-back" @click="$router.push('/subjects/list')" v-if="$route.query.id">返回学科</i>
          <el-button type="success" icon="el-icon-edit" size="mini" @click="addCatalog">新增目录</el-button>
        </div>
      </div>
      <!-- 提示信息 -->
      <div class="tipInfo">
         <el-alert
          :title="'数据一共'+total+'条'"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
      </div>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="序号"
          width="120">
        </el-table-column>
        <el-table-column
          prop="subjectName"
          label="所属学科"
          width="120">
        </el-table-column>
        <el-table-column
          prop="directoryName"
          label="目录名称"
          width="120">
        </el-table-column>
        <el-table-column
          prop="username"
          label="创建者"
          width="120">
        </el-table-column>
        <el-table-column
          prop="addDate"
          label="创建日期"
          width="200">
          <!-- <template slot-scope="scope"> -->
            <span slot-scope="scope">{{scope.row.addDate | parseTimeByString}}</span>
          <!-- </template> -->
        </el-table-column>
        <el-table-column
          prop="totals"
          label="面试题数量"
          width="120">
        </el-table-column>
        <el-table-column
          label="状态"
          width="120">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.state == 1">已启用</el-tag>
            <el-tag type="info" v-else>已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="150">
          <template slot-scope="scope">
            <el-button @click="switchState(scope.row,scope.$index)" type="text" size="small">{{scope.row.state===1?"禁用":"启用"}}</el-button>
            <el-button type="text" size="small" :disabled="scope.row.state===1" @click="updateCatalog(scope.row)">修改</el-button>
            <el-button type="text" size="small" :disabled="scope.row.state===1" @click="delCatalog(scope.row,scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
        background
        @size-change="pageSizeChange"
        @current-change="CurrentPageChange"
        :current-page="page"
        :page-sizes="[5, 6, 8, 10]"
        :page-size="pageSize"
        layout="prev, pager, next, sizes, jumper"
        :total="total">
        </el-pagination>
      </div>
      <!-- 修改表格数据弹框 -->
      <el-dialog
        title="修改目录"
        :visible.sync="updateDialog"
        width="30%">
        <!-- <span>这是一段信息</span> -->
        <!-- 表单 -->
        <el-form :model="updateForm" ref="upForm" :inline="true" class="table" :rules="rules">
            <el-form-item label="所属学科" v-if="!$route.query.id">
              <el-select v-model="updateForm.subjectID" placeholder="活动区域">
                <el-option :label="item.subjectName" :value="item.id" v-for="item in subject" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          <el-form-item label="目录名称" prop="cataName">
            <el-input v-model.trim="updateForm.cataName"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="sureUpdate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加目录弹层 -->
      <el-dialog
        title="新增目录"
        :visible.sync="addDialog"
        width="30%">
        <!-- 表单 -->
        <el-form :model="addForm" ref="addForm" :inline="true" class="table" :rules="rules">
            <el-form-item label="所属学科" v-if="!$route.query.id">
              <el-select v-model="addForm.subjectID" placeholder="请选择">
                <el-option :label="item.subjectName" :value="item.id" v-for="item in subject" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          <el-form-item label="目录名称" prop="directoryName">
            <el-input v-model.trim="addForm.directoryName"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeAdd">取 消</el-button>
          <el-button type="primary" @click="sureAdd">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入获取目录相关接口
import { list as cataList, changeState, remove, update, add } from "@/api/hmmm/directorys.js";
// 引入获取学科的接口
import { list as subList } from "@/api/hmmm/subjects.js"
export default {
  data(){
    return {
      formInline:{
        directoryName:"", //目录名称
        state:null, //目录状态
        subjectID:null, //学科id
      },
      tableData:[], //表格数据
      page:1,
      pageSize:10,
      total:0,
      updateDialog:false, //修改数据弹框
      addDialog:false, //新增目录弹层
      updateForm:{
        cataName:"", //目录名称
        subjectID:"", //学科id
        id:null, // 临时学科id
        subName:"", //临时学科名称
      },
      subject:[], //所属学科
      tableID:null, //当前数据行id
      addForm:{ //新增目录
        subjectID:null,
        directoryName:"",
      },
      rules:{
        cataName:[
          {required:true,message:"目录名称不能为空",trigger:"blur"}
        ],
        directoryName:[
          {required:true,message:"目录名称不能为空",trigger:"blur"}
        ]
      }
    }
  },
  methods:{
    // 有条件获取目录列表
    async getcatalog(){
      try{
        const res = await cataList({
          page:this.page,
          pagesize:this.pageSize,
          ...this.formInline,
        });
        console.log(res,"搜索目录列表");
        this.tableData = res.data.items;
        this.total = res.data.counts;
      }catch(err){
        console.log(err);
        this.$message("获取目录列表失败");
      }
    },
    // 获取目录列表
    async getcataList(){
      try{
        if(this.$route.query.id){
          // 从学科跳转过来的
          // 学科id
          let id = this.$route.query.id;
          //存在作用域的问题
          var res = await cataList({
            subjectID:id,
          });
        }else {
          var res = await cataList();
        }
        // console.log(res,"目录列表");
        this.tableData = res.data.items;
        this.total = res.data.counts;
        console.log(this.tableData);
      }catch(err){
          console.log(err);
          this.$message("获取目录列表失败");
        }
    },
    //清空表单的内容
    resetForm(){
      this.$refs.form.resetFields();
    },
    // 搜索
    searchResult(){
      // 获取关键字
      // const form = this.formInline;
      // console.log(form,"搜索");
      // 判断是否为空
      // if(!form.directoryName && !form.state){
      //   this.$message("目录名称或者状态不能为空");
      //   return;
      // }
      // 恢复默认状态
      this.page = 1;
      this.pageSize = 10;
      // 调接口  渲染数据
      this.getcatalog();
    },
    //每页数量改变时
    pageSizeChange(size){
      this.pageSize = size;
      // 每次切换时，从第一页开始显示
      this.page = 1;
      // 调接口
      this.getcatalog();
    },
    // 当前页码改变
    CurrentPageChange(page){
      // 获取当前页
      // 更新page
      this.page = page;
      // 调接口
      this.getcatalog();
    },
    // 更改表格数据的状态
    async switchState(row,index){
      let tabState = row.state;
      let state = tabState===1?0:1;
      // 调接口更改后台state状态
      try{
        const res = await changeState({
          id:row.id,
          state:state,
        });
        console.log(res,"修改状态");
        // 更新视图
        // 方式一：更改当前组件的tableData
        // this.tableData[index].state = state;
        // 方式二：
        // 直接更改scope.row里对应的state状态，因为scope.row是一个对象，这样可以直接更改子组件里的数据
        row.state = state;
      }catch(err){
        console.log(err);
        this.$message("更改状态失败");
      }
    },
    // 删除目录
    delCatalog(row,index){
      // 拿到当前行数据id
      let id = row.id;
      // 确认弹框
      this.$confirm('此操作将永久删除该目录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {

          try{
            // 调接口
            const res = await remove({
              id:id
            });
            console.log(res,"删除目录");
            // 更新视图
            // this.tableData.splice(index,1);
            if(this.tableData.length === 1){
              if(this.page > 1){
                this.page = this.page - 1;
              }
            }
            // 重新调接口渲染数据
            this.getcatalog();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }catch(err){
            console.log(err);
            this.$message('删除失败');
          }
        }).catch(() => {
          this.$message('已取消删除');
        });
    },
    // 打开修改弹框 数据回填
    updateCatalog(row,index){
      this.tableID = row.id;
      console.log(row,"xiugai");
      // 打开弹框
      this.updateDialog = true;
      // 判断是否是从学科跳转过来的
      if(!this.$route.query.id){
        // 获取学科信息，渲染
        this.getSubjectList();
        this.updateForm.subjectID = row.subjectName;
        this.updateForm.subName = row.subjectName;
      }
      // 数据回填
      this.updateForm.cataName = row.directoryName;
      this.updateForm.id = row.subjectID;
      // console.log(this.updateForm,"ceshi");
    },
    // 确认修改
    sureUpdate(){
      // 表单验证
      this.$refs["upForm"].validate((valid)=>{
        if(valid){
          let subID;
          // 拿到修改之后的数据
          if(this.updateForm.subjectID === this.updateForm.subName){
            // 说明学科没有切换
            subID = this.updateForm.id;
          }else {
            subID = this.updateForm.subjectID;
          }
          console.log(subID,"学科id");
          // 判断学科id是否存在
          // 调接口修改
          this.updateCate({
            id:this.tableID,
            subjectID:subID,
            directoryName:this.updateForm.cataName,
          });
          // 关闭弹框
          this.updateDialog = false;
        }else {
          // console.log(111);
          return false;
        }
      }); 
    },
    // 取消修改目录弹层
    closeDialog(){
      // 清除验证规则 恢复默认状态
      this.$refs["upForm"].resetFields();
      // 关闭弹层
      this.updateDialog = false;
    },
    // 修改目录
    async updateCate(data){
      try{
        const res = await update(data);
        // 更新视图
        // console.log(res,"修改目录返回的结果");
        this.getcatalog();
        this.$message("修改成功");
      }catch(err){
        console.log(err);
        this.$message("修改目录失败");
      }
    },
    // 获取学科列表
    async getSubjectList(){
      try{
        const res = await subList();
        // console.log(res,"xueke");
        this.subject = res.data.items;
      }catch(err){
        console.log(err);
        this.$message({
          message:"获取学科列表失败",
          type:"error",
        });
      }
    },
    // 新增目录
    addCatalog(){
      // 打开弹层
      this.addDialog = true;
      // 根据是否从学科跳转，渲染学科列表
      if(!this.$route.query.id){
        this.getSubjectList();
      }
    },
    // 确认新增
    sureAdd(){
      // 验证表单
      // 分是否是学科跳转过来的
      if(!this.$route.query.id){
        // 验证所属学科
        if(!this.addForm.subjectID){
          this.$message("请选择所属学科");
          return;
        }
      }
      // 验证目录名称
      this.$refs["addForm"].validate(async (valid)=>{
        if(valid){
           // 调接口新增目录
           const id = this.$route.query.id;
          try{
            if(id){
              // this.addForm.subjectID = 4;
              // this.addForm.directoryName = 'aaaa';
              this.addForm.subjectID =Number(id);
            }
              // console.log('----->',this.addForm);
            const res = await add(this.addForm);
            console.log(res,"新增的目录");
            // 更新本地
            this.getcataList();
          }catch(err){
            console.log(err);
            this.$message("新增目录失败");
          }
          // 清空输入框的值
          this.addForm.directoryName ="";
          // 关闭弹层
          this.addDialog = false;
        }else {
          return false;
        }
      });
    },
    // 取消新增目录
    closeAdd(){
      // 清除验证规则 恢复默认状态
      this.$refs["addForm"].resetFields();
      this.addForm.subjectID = null;
      // 关闭弹层
      this.addDialog = false;
    }
  },
  mounted(){
    this.getcataList();
    if(this.$route.query.id){
      this.formInline.subjectID = this.$route.query.id;
    }
  }
}
</script>

<style scoped lang='less'>
.formData {
  position: relative;
  .rightAdd {
    position: absolute;
    right: 0px;
    top: 0px;
    .el-icon-back {
      font-size: 15px;
      margin-right: 10px;
      color: #57aaff;
      cursor: pointer;
    }
  }
}
.tipInfo {
  margin-bottom: 10px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.table {
  text-align: center;
}

</style>
